import datetime
import sys
import time

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor
from PyQt5.QtWidgets import *
from UI.MainWindows import Ui_MainWindow
from Mode.SQLiteMode import SQLite
from Mode.Example import Example
from Mode.Log import Log
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QThread, pyqtSignal
import Mode.GetFundProcess as fundFun


class updateFundInfo(QThread):
    trigger = pyqtSignal()
    def run(self):
        while True:
            time.sleep(5)
            Log("Thread1", "开始更新")
            self.trigger.emit()

Tag = "Main"


class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        self.db = "./Data.db"
        self.bar = {}
        self.initShowBar()
        self.initEstimatedInvestmentAmount()
        self.initReserveInputAmount()
        self.initFundParticualrs()
        self.thread1 = updateFundInfo()
        self.thread1.trigger.connect(self.initFundParticualrs)
        self.thread1.start()
        # 设置单元格不可编辑 2021/12/12 14:15 By Wangxc_a_bj
        self.FundParticualrs.setEditTriggers(QTableWidget.NoEditTriggers)
        self.FundParticualrs.doubleClicked.connect(lambda: self.change_func())

    def initShowBar(self):
        # 连接数据库获取配置信息 2021/12/11 22:23 By Wangxc_a_bj
        example = Example() \
            .andEqualTo("config_key", "ShowBarConfig") \
            .andEqualTo("config_group", "Show_Bar")
        values = SQLite(self.db).select("sys_config", example)[0][2].split(",")
        Log(Tag,values)
        bar = ["基金名称", "基金代码", "估值", "持仓价", "持仓数", "持有金额", "涨跌幅", "当前收益", "收益率", "总收益"]
        barLenght = [150, 60, 50, 70, 70, 80, 60, 60, 50, 60]
        config = []
        configLenght  = []
        num = 0
        for i in range(len(values)):
            Log(Tag,f"values[{i}]:{values[i]},bar[{i}]:{bar[i]}")
            if values[i]=="true":
                config.append(bar[i])
                configLenght.append(barLenght[i])
                self.bar[bar[i]] = num
                num += 1
        Log(Tag, config)
        Len = len(config)
        # self.bar=config
        # 设置展示信息栏 2021/12/11 22:42 By Wangxc_a_bj
        self.FundParticualrs.setColumnCount(Len)
        for i in range(Len):
            item = QtWidgets.QTableWidgetItem(config[i])
            self.FundParticualrs.setHorizontalHeaderItem(i, item)
            self.FundParticualrs.setColumnWidth(i, configLenght[i])

    def initEstimatedInvestmentAmount(self):
        # 设置预计投入金额 2021/12/11 23:12 By Wangxc_a_bj
        example = Example() \
            .andEqualTo("config_key", "EstimatedInvestmentAmount") \
            .andEqualTo("config_group", "Show_Bar")
        values = SQLite(self.db).select("sys_config", example)[0][2]
        self.EstimatedInvestmentAmount.setValue(float(values))

    def initReserveInputAmount(self):
        # 设置备用投入金额 2021/12/11 23:23 By Wangxc_a_bj
        example = Example() \
            .andEqualTo("config_key", "ReserveInputAmount") \
            .andEqualTo("config_group", "Show_Bar")
        values = SQLite(self.db).select("sys_config", example)[0][2]
        self.ReserveInputAmount.setValue(float(values))

    def initFundParticualrs(self):
        Log(Tag, f"self.bar:{self.bar}")
        # 设置基金列表 2021/12/11 23:32 By Wangxc_a_bj
        values = SQLite(self.db).select("fund_information")
        Log(Tag, values)
        Len = len(values)+1
        totalPrice = 0
        self.FundParticualrs.setRowCount(Len)
        # for i in self.bar.keys():
        #     item = QtWidgets.QTableWidgetItem("")
        #     if i != "基金代码":
        #         item.setFlags(QtCore.Qt.ItemFlag(0))
        #         item.setFlags(QtCore.Qt.ItemIsEnabled)
        #     self.FundParticualrs.setItem(0, self.bar[i], item)

        for i in range(1,Len):
            fundName = values[i-1][1]
            fundCode = values[i-1][2]
            positionPrice = values[i-1][3]
            positionNumber = values[i-1][4]
            lastInfo = fundFun.GetFundJsonInfo(fundCode)
            lsjz = fundFun.GetlsjzInfo(fundCode)
            Log(Tag,lastInfo)
            # 持有成本金额 2021/12/12 0:03 By Wangxc_a_bj
            position = float(positionPrice)*float(positionNumber)
            totalPrice += position
            if "基金名称" in self.bar.keys():
                item = QtWidgets.QTableWidgetItem(fundName)
                item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                # item.setFlags(QtCore.Qt.ItemFlag(0))
                # item.setFlags(QtCore.Qt.ItemIsEnabled)
                self.FundParticualrs.setItem(i, self.bar["基金名称"], item)
            if "基金代码" in self.bar.keys():
                item = QtWidgets.QTableWidgetItem(fundCode)
                item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                # item.setFlags(QtCore.Qt.ItemFlag(0))
                # item.setFlags(QtCore.Qt.ItemIsEnabled)
                self.FundParticualrs.setItem(i, self.bar["基金代码"], item)
            if "持仓价" in self.bar.keys():
                item = QtWidgets.QTableWidgetItem(positionPrice)
                item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.FundParticualrs.setItem(i, self.bar["持仓价"],item)
            if "持仓数" in self.bar.keys():
                item = QtWidgets.QTableWidgetItem(positionNumber)
                item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.FundParticualrs.setItem(i, self.bar["持仓数"], item)
            if "持有金额" in self.bar.keys():
                # 持有金额 2021/12/12 0:10 By Wangxc_a_bj
                PriceLatest = round(float(lsjz[0][1])*float(positionNumber), 2)
                item = QtWidgets.QTableWidgetItem(str(PriceLatest))
                item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                # item.setFlags(QtCore.Qt.ItemFlag(0))
                # item.setFlags(QtCore.Qt.ItemIsEnabled)
                self.FundParticualrs.setItem(i, self.bar["持有金额"], item)
            if "估值" in self.bar.keys():
                item = QtWidgets.QTableWidgetItem(lastInfo['gsz'])
                item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                # item.setFlags(QtCore.Qt.ItemFlag(0))
                # item.setFlags(QtCore.Qt.ItemIsEnabled)
                self.FundParticualrs.setItem(i, self.bar["估值"], item)
            if "涨跌幅" in self.bar.keys():
                # temp = float(lastInfo[6])
                # temp = lastInfo['gszzl']
                item = QtWidgets.QTableWidgetItem(lastInfo['gszzl']+"%")
                if float(lastInfo['gszzl'] )>= 0:
                    item.setBackground(QColor(255,0,0))
                else:
                    item.setBackground(QColor(0, 255, 0))
                item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                # item.setFlags(QtCore.Qt.ItemFlag(0))
                # item.setFlags(QtCore.Qt.ItemIsEnabled)
                self.FundParticualrs.setItem(i, self.bar["涨跌幅"], item)
            if "当前收益" in self.bar.keys():
                t1 = datetime.date(*map(int, lastInfo['jzrq'].split('-')))
                t2 = datetime.date(*map(int, lsjz[0][0].split('-')))
                # 当净值为最近净值时，按照估值来进行计算，否则按照最新净值来进行计算 2021/12/12 13:49 By Wangxc_a_bj
                if t1 == t2:
                    temp = round(float(lastInfo['gszzl'])*float(lastInfo['dwjz'])*float(positionNumber),2)
                else:
                    temp = round((float(lsjz[0][1])-float(lastInfo['dwjz']))*float(positionNumber),2)
                # temp = round((float(lastInfo[1]) - float(lastInfo[4]))*float(values[i-1][4]), 2)
                item = QtWidgets.QTableWidgetItem(str(temp))
                item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                # item.setFlags(QtCore.Qt.ItemFlag(0))
                # item.setFlags(QtCore.Qt.ItemIsEnabled)
                self.FundParticualrs.setItem(i, self.bar["当前收益"], item)

            if "收益率" in self.bar.keys():
                temp = round(((float(lsjz[0][1])/float(positionPrice))-1)*100,2)
                item = QtWidgets.QTableWidgetItem(str(temp)+"%")
                if temp >= 0:
                    item.setBackground(QColor(255,0,0))
                else:
                    item.setBackground(QColor(0, 255, 0))
                item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                # item.setFlags(QtCore.Qt.ItemFlag(0))
                # item.setFlags(QtCore.Qt.ItemIsEnabled)
                self.FundParticualrs.setItem(i, self.bar["收益率"], item)
            if "总收益" in self.bar.keys():
                temp = round((float(lsjz[0][1])-float(positionPrice))*float(positionNumber),2)
                item = QtWidgets.QTableWidgetItem(str(temp))
                item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                # item.setFlags(QtCore.Qt.ItemFlag(0))
                # item.setFlags(QtCore.Qt.ItemIsEnabled)
                self.FundParticualrs.setItem(i, self.bar["总收益"], item)
        # 设置已经投入金额 2021/12/12 0:49 By Wangxc_a_bj
        temp = f"<html><head/><body><p><span style=\" font-size:16pt;\">￥{str(round(totalPrice,2))}</span></p></body></html>"
        self.AmountInvested.setText(temp)
        # 设置个人基金仓位 2021/12/12 0:50 By Wangxc_a_bj
        temp = round(totalPrice/float(self.EstimatedInvestmentAmount.text())*100,2)
        if temp > 100:
            temp = f"<html><head/><body><p><span style=\" font-size:16pt; color:#ff0000; \">{str(temp)}%</span></p></body></html>"
        else:
            temp = f"<html><head/><body><p><span style=\" font-size:16pt;\">{str(temp)}%</span></p></body></html>"
        self.PersonalFundPosition.setText(str(temp)+"%")

    def resizeEvent(self, *args, **kwargs):
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(5, 5, self.width() - 10, self.height() - 10))
        # self.gridLayout.setGeometry(QtCore.QRect(0, 45, self.width(), self.height()-45))

    def change_func(self):
        line = self.FundParticualrs.currentRow()
        Column = self.FundParticualrs.currentColumn()
        print(line,Column)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())
